import React from 'react';
import PropTypes from 'prop-types';
import { Form, Field, Input, Radio, DatePicker, Button, Message, Balloon } from '@teamix/ui';
import { YunxiaoIcon } from '@alife/devops-ui';
import dayjs from 'dayjs';
import ListEmpty from 'components/PersonalSettings/components/ListEmpty';
import ListLoading from 'components/PersonalSettings/components/ListLoading';
import SshItem from './sshItem';
import exceed from 'utils/apimap';
import './index.scss';
// import track from 'utils/track';
import intl from 'components/PersonalSettings/components/locale';

const FormItem = Form.Item;

const prefix = 'ssh-secret';

class SshKey extends React.Component {
  static propTypes = {
    // 默认为吊顶,
    page: PropTypes.string,
    vpc: PropTypes.bool,
    vpc_doc: PropTypes.object,
  };

  static defaultProps = {
    page: 'Ceiling-SSH Keys',
    vpc: false,
    vpc_doc: {},
  };

  constructor(props) {
    super(props);
    this.field = new Field(this);
    this.state = {
      submitting: false,
      keys: [],
      total: 0,
      isLoadingTable: true,
    };
  }

  componentDidMount() {
    this.getKeys();
  }

  onKeyInputChange = (value) => {
    const key = value.trim();
    const strArr = key.split(' ');
    const title = strArr[strArr.length - 1];

    this.field.setValue('key', value);
    if (strArr.length > 1) {
      this.field.setValue('title', title);
    }
  };

  handleSubmit = () => {
    this.field.validate((errors) => {
      if (!errors) {
        this.setState({ submitting: true });
        const formData = this.field.getValues();
        if (formData.expire_time) {
          formData.expire_time = dayjs(formData.expire_time).format('YYYY-MM-DD HH:mm:ss');
        }
        this.postKey(formData, (isFail) => {
          if (!isFail) {
            this.field.reset();
          }
          this.setState({ submitting: false });
        });
      }
    });
  };

  getKeys = () => {
    exceed[this.props.vpc ? 'fetch' : 'forceFetch']({
      api: this.props.vpc ? 'vpc.keys.list' : 'keys.list',
      data: {
        page: 1,
        per_page: 100,
      },
    }).then((result) => {
      const { list } = result;
      if (list === null) {
        this.setState({
          keys: [],
          total: 0,
          isLoadingTable: false,
        });
      } else {
        this.setState({
          keys: list,
          total: list.length,
          isLoadingTable: false,
        });
      }
    });
  };

  postKey = (formData, cb) => {
    exceed
      .fetch({
        api: this.props.vpc ? 'vpc.keys.post' : 'keys.post',
        data: {
          ...formData,
          keys_type: 'PersonalKey',
        },
      })
      .then((result) => {
        if (result && result.id) {
          setTimeout(() => {
            Message.success({
              title: '添加成功',
            });
          }, 500);
          this.getKeys();

          // track({
          //   action: 'add_ssh',
          //   page: 'Dialog-SSH Keys',
          //   type: '',
          //   control: '',
          // });
        } else if (result && result.message) {
          Message.error({
            title: result.message,
          });
        }

        cb && cb();
      })
      .catch((err) => {
        let errorInfo = '';
        try {
          const responseText = JSON.parse(err.responseText);
          errorInfo = responseText.message || responseText.errorCode;
        } catch (e) {
          errorInfo = intl.get({
            id: 'code-assets.components.commitDetail.TheSystemIsBusyPlease',
            defaultMessage: '系统繁忙，请稍后重试',
          });
        }

        Message.error({
          title: errorInfo,
        });

        // 接口报错也要回调，以让按钮取消loading状态
        cb && cb('isFail');
      });
  };

  checkKey = (rule, value, callback) => {
    if (value.indexOf('ssh-rsa') !== 0 && value.indexOf('ssh-ed25519') !== 0) {
      return callback(intl.get('only_support_rsa_algorithm'));
    } else {
      return callback();
    }
  };

  disabledDate = (date) => {
    return date.valueOf() <= dayjs().valueOf();
  };

  render() {
    const { init } = this.field;
    const { vpc } = this.props;
    const { keys, total, isLoadingTable } = this.state;
    const expire_time_label = (
      <span>
        {intl.get('ssh_expire_time')}
        <Balloon.Tooltip
          type="primary"
          trigger={<YunxiaoIcon type="question-line" size="small" />}
          align="t"
        >
          {intl.get('ssh_expire_time_question')}
        </Balloon.Tooltip>
      </span>
    );
    return (
      <div style={{ marginLeft: 20, marginRight: 20, width: 590, minHeight: 600 }}>
        <div className={`${prefix}-title`}>{intl.get('add_ssh_keys')}</div>
        <Form field={this.field}>
          <FormItem label={intl.get('key')} required>
            <div className="add-key-tip">
              {intl.get('before_ssh_clone_need')}
              <a
                href={
                  vpc
                    ? this.props.vpc_doc['ssh-keys']
                    : 'https://help.aliyun.com/document_detail/153709.html'
                }
                target="_blank"
                rel="noopener noreferrer"
              >
                {intl.get('generate_ssh_key')}
              </a>
            </div>
            <Input.TextArea
              {...init('key', {
                rules: [
                  { required: true, message: intl.get('item_necessary'), trigger: ['onKeyUp'] },
                  { validator: this.checkKey, trigger: ['onKeyUp'] },
                ],
              })}
              placeholder={intl.get('please_plaste_your_ssh_key')}
              onChange={this.onKeyInputChange}
            />
          </FormItem>
          <FormItem label={intl.get('item_title')} required>
            <Input
              {...init('title', {
                rules: [{ required: true, message: intl.get('item_necessary') }],
              })}
              placeholder={intl.get('please_input_key_title')}
            />
          </FormItem>
          {vpc ? null : (
            <FormItem label={intl.get('scope')} required>
              <Radio.Group
                {...init('key_scope', {
                  initValue: 'ALL',
                  rules: [{ required: true, message: intl.get('item_necessary') }],
                })}
              >
                <Radio value="ALL">{intl.get('scope_all')}</Radio>
                <Radio value="READ">{intl.get('scope_only_read')}</Radio>
              </Radio.Group>
            </FormItem>
          )}
          {vpc ? null : (
            <FormItem label={expire_time_label}>
              <DatePicker
                disabledDate={this.disabledDate}
                {...init('expire_time', {
                  rules: [{ required: false }],
                })}
              />
            </FormItem>
          )}
          <FormItem label="">
            <Button type="primary" onClick={this.handleSubmit} loading={this.state.submitting}>
              {intl.get('item_add')}
            </Button>
          </FormItem>
        </Form>
        <div className={`${prefix}-divide`} />
        {!isLoadingTable ? (
          <div style={{ marginTop: 30, marginBottom: 30 }}>
            <div className={`${prefix}-title`}>{`${intl.get('has_keys')} · ${total}`}</div>
            {keys && keys.length > 0 ? (
              <div>
                {keys.map((item) => (
                  <SshItem
                    key={item.id}
                    dataSource={item}
                    getKeys={this.getKeys}
                    uiless_config={window.UILessConfig}
                    vpc={vpc}
                  />
                ))}
              </div>
            ) : (
              <ListEmpty content={intl.get('no_data')} imgType="data" />
            )}
          </div>
        ) : (
          <ListLoading />
        )}
      </div>
    );
  }
}

export default SshKey;
